<template>
    <el-form label-width="100px">
        <el-row>
            <!-- 在同一行的表单项 -->
            <el-col :span="12">
                <el-form-item label="栏目标题">
                    <el-input v-model="formParams.columnTitle" placeholder="栏目标题"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="标签">
                    <el-tag style="margin:0px 5px" v-for="tag in dynamicTags" :key="tag" closable
                        :disable-transitions="false" @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                        @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">
                        + New Tag
                    </el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="6">
                <el-form-item label="栏目类型">
                    <el-select v-model="formParams.columnType.typeId">
                        <el-option v-for="(item, index) in allColumnType" :key="item.typeId" :label="item.typeName"
                            :value="item.typeId"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="作者">
                    <el-select v-model="formParams.author.authorId">
                        <el-option v-for="(item, index) in allWriter" :key="item.authorId" :label="item.nickName"
                            :value="item.authorId"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="年级">
                    <el-select v-model="formParams.age.ageId">
                        <el-option v-for="(item, index) in allAge" :key="item.ageId" :label="item.phase"
                            :value="item.ageId"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="6">
                <el-form-item label="是否显示" prop="display">
                    <el-radio-group v-model="formParams.display" class="ml-4">
                        <el-radio :label="1" size="large">显示</el-radio>
                        <el-radio :label="0" size="large">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="是否推荐" prop="recommend">
                    <el-radio-group v-model="formParams.recommend" class="ml-4">
                        <el-radio :label="1" size="large">推荐</el-radio>
                        <el-radio :label="0" size="large">不推荐</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="6">
                <el-form-item label="排序" prop="columnSeq">
                    <el-input v-model="formParams.columnSeq" placeholder="1"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="推广返现" prop="reward">
                    <el-input v-model="formParams.reward" placeholder="0"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="是否免费" prop="charge">
                    <el-radio-group v-model="formParams.charge" class="ml-4">
                        <el-radio :label="1" size="large">收费</el-radio>
                        <el-radio :label="0" size="large">免费</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="价格" prop="price" label-width="50px">
                    <el-input v-model="formParams.price" placeholder="价格"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="封面图" prop="display">
                    <el-upload v-model:file-list="imgList" action="/api/v1/m/upload" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handlerUpload">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width:100%;height: 100%;" />
                    </el-dialog>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="摘要" prop="summary">
                    <el-input type="textarea" :rows="6" v-model="formParams.summary" placeholder="栏目摘要"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item label="栏目html" prop="columnIntro">
                    <!-- <el-input type="textarea" :rows="6" v-model="formParams.columnIntro" placeholder="栏目htm"></el-input> -->
                    <WangEditor v-model="formParams.columnIntro"></WangEditor>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item>
                    <el-button :disabled="formParams.columnTitle.length > 0 ? false : true" type="primary" size="default"
                        @click="save">保存</el-button>
                    <el-button type="primary" size="default" @click="cancel">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElInput } from 'element-plus'
import type { TColumn } from '@/api/content/column/type'
import { reqAddOrUpdateColumn } from '@/api/content/column'

import { reqColumnTypeList } from '@/api/content/columntype'
import type { TColumnType, TColumnTypeListResponseData, } from '@/api/content/columntype/type'

import { reqWriterList } from '@/api/acl/writer';
import type { TWriterListResponseData, TWriter } from '@/api/acl/writer/type'

import { reqAgeList } from '@/api/content/age';
import type { TAgeListResponseData, TAge } from '@/api/content/age/type'

import type { UploadProps, UploadUserFile } from 'element-plus'

import { ElMessage } from 'element-plus'

let $emit = defineEmits(['changeScene'])
//点击取消按钮:通知父组件切换场景为1,展示有的SPU的数据
const cancel = () => {
    $emit('changeScene', { flag: 0, params: 'update' })
}

const inputValue = ref('')
const dynamicTags = ref<string[]>([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const handleClose = (tag: string) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        dynamicTags.value.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

let allColumnType = ref<TColumnType[]>([])
let allWriter = ref<TWriter[]>([])
let allAge = ref<TAge[]>([])

//商品图片
let imgList = ref<UploadUserFile[]>([
    {
        'url': '',
        name: ''
    }, {
        'url': '',
        name: ''
    }
])

//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
//存储预览图片地址
let dialogImageUrl = ref<string>('')
//存储已有的SPU对象
let formParams = ref<TColumn>({
    columnId: '',
    columnTitle: '',
    columnCover1: '',
    columnCover2: '',
    columnIntro: '',

    charge: 0,
    price: 0,
    reward: 0,
    display: 0,
    recommend: 0,
    columnSeq: 0,

    tag: '',
    summary: '',
    sets: 0,
    author: {
        nickName: '',
    },
    age: {

    },
    columnType: {
        typeId: 0
    },
})

let content = ref('aaaa')

const resetForms = () => {
    // formParams.authorId = ''

}

const initAllColumnType = async () => {
    let result: TColumnTypeListResponseData = await reqColumnTypeList(1, 100, '')
    allColumnType.value = result.data.list
}

const initAllWriter = async () => {
    let result: TWriterListResponseData = await reqWriterList(1, 100, '')
    allWriter.value = result.data.list
}
const initAllAge = async () => {
    let result: TAgeListResponseData = await reqAgeList(1, 100, '', '')
    allAge.value = result.data.list
}

const resetImgList = () => {
    let imgList = [
        {
            'url': '',
            name: ''
        }, {
            'url': '',
            name: ''
        }
    ]
}
const initHasColumnData = async (column: TColumn) => {
    formParams.value = column
    if (!formParams.value.author) {
        formParams.value.author = {
            authorId: '',
            nickName: ''
        }
    }
    if (!formParams.value.columnType) {
        formParams.value.columnType = {
            typeId: 0,
        }
    }
    if (!formParams.value.age) {
        formParams.value.age = {
            ageId: 0,
        }
    }

    if (column && column.tag) {
        dynamicTags.value = column.tag.split(',');
    }
    initAllColumnType()
    initAllWriter()
    initAllAge()
    resetImgList()
    let url = formParams.value.columnCover1;
    if (url !== undefined) {
        imgList.value[0].url = url;
        imgList.value[0].name = url.substring(url.lastIndexOf('/') + 1);
    }
    url = formParams.value.columnCover2;
    if (url !== undefined) {
        imgList.value[1].url = url;
        imgList.value[1].name = url.substring(url.lastIndexOf('/') + 1);
    }
}
//照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url
    //对话框弹出来
    dialogVisible.value = true
}
//照片墙删除文件钩子
const handleRemove = () => {
    console.log(123)
}
//照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
    if (
        file.type == 'image/png' ||
        file.type == 'image/jpeg' ||
        file.type == 'image/gif'
    ) {
        if (file.size / 1024 / 1024 < 3) {
            return true
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件务必小于3M',
            })
            return false
        }
    } else {
        ElMessage({
            type: 'error',
            message: '上传文件务必PNG|JPG|GIF',
        })
        return false
    }
}


//保存按钮的回调
const save = async () => {
    //1:照片墙的数据
    if (imgList.value[0] && typeof imgList.value[0].response === 'object' && imgList.value[0].response !== null) {
        const responseData = imgList.value[0].response as { data: { url: string } };
        if (responseData.data && responseData.data.url) {
            formParams.value.columnCover1 = responseData.data.url;
        } else {
            formParams.value.columnCover1 = imgList.value[0].url;
        }
    } else if (imgList.value[0] && imgList.value[0].url) {
        formParams.value.columnCover1 = imgList.value[0].url;
    }

    if (imgList.value[0] && typeof imgList.value[1].response === 'object' && imgList.value[1].response !== null) {
        const responseData = imgList.value[1].response as { data: { url: string } };
        if (responseData.data && responseData.data.url) {
            formParams.value.columnCover2 = responseData.data.url;
        } else {
            formParams.value.columnCover2 = imgList.value[1].url;
        }
    } else if (imgList.value[1] && imgList.value[1].url) {
        formParams.value.columnCover2 = imgList.value[1].url;
    }

    formParams.value.tag = dynamicTags.value.join(",")
    //2:整理销售属性的数据
    let result = await reqAddOrUpdateColumn(formParams.value)
    if (result.code == 0) {
        ElMessage({
            type: 'success',
            message: formParams.value.columnId ? '更新成功' : '添加成功',
        })
        //通知父组件切换场景为0
        $emit('changeScene', {
            flag: 0,
            params: formParams.value.columnId ? 'update' : 'add',
        })
    } else {
        ElMessage({
            type: 'success',
            message: formParams.value.columnId ? '更新成功' : '添加成功',
        })
    }
}

//初始化请求方法，父组件会引用
const initAddColumn = async () => {
    //清空数据
    Object.assign(formParams.value, {
        columnId: '',
        columnTitle: '',
        columnCover1: '',
        columnCover2: '',
        columnIntro: '',

        charge: 0,
        price: 0,
        reward: 0,
        display: 0,
        recommend: 0,
        columnSeq: 0,

        tag: '',
        summary: '',
        sets: 0,
        author: {
            nickName: '',
        },
        age: {

        },
        columnType: {
            typeId: 0
        },
    })
    //清空照片
    imgList.value = []


    //获取全部品牌的数据
    initAllColumnType()
    initAllWriter()
    initAllAge()

}
//对外暴露
defineExpose({ initHasColumnData, initAddColumn })
</script>

<style scoped></style>
